#!/usr/bin/python

import pygame
from pygame.locals import *
from sys import exit
import Character
import MapLoader
import Map
import Block
import Room


pygame.init()

# Constants
BLOCK_SIZE_X = 64
BLOCK_SIZE_Y = 64


# Map object setup
loader = MapLoader.MapLoader('/home/thomp/pygame/thomp-rpg/build2/maps')
screen = pygame.display.set_mode((640,640), 0, 32)
level_1_map = loader.loadLevel1()

# Character object setup
start_block = level_1_map.getActiveRoom().getCharBlock()
player = Character.Character(True, start_block, 64, 64)
player.loadSpriteSheets()
leftSpriteSheet = player.getLeftSpriteSheet()
rightSpriteSheet = player.getRightSpriteSheet()
frame_index = 0
image = rightSpriteSheet[frame_index]


def updateBackground( map_screen ):
	global screen
	screen.blit(map_screen.getImage(), (0,0))

def updateCharacter( player, sprite ):
	global image
	screen.blit(sprite, player.getPosition())
	image = sprite

def move( x, y, current_map, spritesheet ):
	new_x = player.getX()/BLOCK_SIZE_X + x/BLOCK_SIZE_X
	new_y = player.getY()/BLOCK_SIZE_Y + y/BLOCK_SIZE_Y
	nextBlock = current_map.getRoom()[new_x][new_y]
	# check to see if next block is a wall
	if nextBlock.isWall:
		return
	# check to see if player needs to be transitioned to another room
	elif nextBlock.hasTransition:
		player.setPosition((nextBlock.getDestinationX() + 1)*BLOCK_SIZE_X, (nextBlock.getDestinationY() +1)*BLOCK_SIZE_Y)
		current_map.makeActive(False)
		nextBlock.getDestinationRoom().makeActive(True)
		updateBackground( nextBlock.getDestinationRoom() )
		updateCharacter(player, spritesheet[0])
		pygame.display.update()
		return
	for spriteframe in spritesheet:
		x_add = x/len(spritesheet) 
		y_add = y/len(spritesheet) 
		player.setPosition( player.getX() + x_add, player.getY() + y_add )
		updateBackground(current_map)
		pygame.time.delay(50)
		updateCharacter(player,spriteframe)
		pygame.display.update()
	# set up block states
	player.getCurrentBlock().setChar(False)
	nextBlock.setChar(True, player)
	

while True:

	t = pygame.time.get_ticks()

	for event in pygame.event.get():
		if event.type == QUIT:
			exit()

	pressed_keys = pygame.key.get_pressed()

	current_map = level_1_map.getActiveRoom()

	# Left Arrow or A movement
	if pressed_keys[K_LEFT] or pressed_keys[K_a]:
		move( -BLOCK_SIZE_X, 0, current_map, leftSpriteSheet )
	## Right Arrow or D movement
	elif pressed_keys[K_RIGHT] or pressed_keys[K_d]:
		move( BLOCK_SIZE_X, 0, current_map, rightSpriteSheet )
	# Up Arrow or W movement
	if pressed_keys[K_UP] or pressed_keys[K_w]:
		move( 0, -BLOCK_SIZE_Y , current_map, leftSpriteSheet )
	# Down Arrow or S movement
	elif pressed_keys[K_DOWN] or pressed_keys[K_s]:
		move( 0, BLOCK_SIZE_Y , current_map, leftSpriteSheet )

	screen.blit(current_map.getImage(), (0,0))
	screen.blit(image, player.getPosition()) 
	
	pygame.display.update()
